package org.arkeologgr.appening.dataacess;

import java.util.ArrayList;
import java.util.List;

import org.arkeologgr.appening.domain.CultureItem;
import org.arkeologgr.appening.parser.ParserJson;

import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.util.Log;

//import com.capgemini.appening.parser.ParserXml;
import com.google.android.maps.GeoPoint;

public class DataAccessManager {
	
	
	public interface CultureItemListListener{
		public void onCultureItemsReceived(List<CultureItem> items);
		public void onCultureItemFailed(String reason);
	}
	
	public interface AddCultureItemListener{
		public void onCultureItemAdded();
		public void onCultureItemAddFail(String reason);
	}
	
	public interface CultureItemListener{
		public void onCultureItemReceived(CultureItem item);
		public void onCultureItemReceiveFailed(String reason);
	}

	protected static final String TAG = "DataAccessManager";
	
	// Singleton instance
	private static DataAccessManager sInstance;

	/**
	 * Set up singleton. Call this method before first use
	 */
	public static void setup() {
		if(sInstance == null){
			sInstance = new DataAccessManager();
		}
	}

	/**
	 *  Tear down singleton
	 */
	public static void tearDown() {
		sInstance = null;
	}
	
	public static DataAccessManager getInstance(){
		return sInstance;
	}
	
	/**
	 * private singleton constructor
	 */
	public DataAccessManager(){}
	
	private List<CultureItem> recentMapItems;
	
	public List<CultureItem>getRecentMapItems(){
		return recentMapItems;
	}
	
	public void getCultureItemsForPosition(final GeoPoint mapCenter, int width, int height, final CultureItemListListener listener){
		
		//Return mock data for now
		List<CultureItem> items = new ArrayList<CultureItem>();
		
		float lat = mapCenter.getLatitudeE6()/(1000*1000);
		float lon = mapCenter.getLongitudeE6()/(1000*1000);
		
	
		//float e6 = 1000*1000;
		//items.add(new CultureItem(CultureItemType.KSamItemType, mapCenter));
		//makeMockData(items);
		/*
		items.add(new CultureItem(1, "bla bla desc2", new GeoPoint((int)(59.1*e6), (int)(18.1*e6)),CultureItemType.UserGeneratedItem,"http://digitaltmuseum.se/thumbnail.do?type=Thing&amp;owner=S-NM&amp;identifier=NM.0151866", "title title2"));
		items.add(new CultureItem(CultureItemType.KSamItemType, new GeoPoint((int)(59.2*e6), (int)(18.2*e6))));
		items.add(new CultureItem(CultureItemType.UserGeneratedItem, new GeoPoint((int)(59.3*e6), (int)(18.3*e6))));
		items.add(new CultureItem(CultureItemType.KSamItemType, new GeoPoint((int)(59.4*e6), (int)(18.4*e6))));
		items.add(new CultureItem(CultureItemType.UserGeneratedItem, new GeoPoint((int)(59.5*e6), (int)(18.5*e6))));*/
		
		//recentMapItems = items;
		//listener.onCultureItemsReceived(items);
		
		AsyncTask<Object, Void, List<CultureItem>> task = new AsyncTask<Object, Void, List<CultureItem>>(){

			String errorMessage = "";
			protected List<CultureItem> doInBackground(Object... params) {
				GeoPoint mapCenter = (GeoPoint)params[0];
				int height = (Integer)params[1];
				int width = (Integer)params[2];
				List<CultureItem> items = getCultureItemsAtMyLocation(mapCenter, height, width);
				return items;
			}

			private List<CultureItem> getCultureItemsAtMyLocation(
					GeoPoint myPosition, int height, int length) {

				
				//ParserJson parser = new ParserJson();
				//ParserXml parser = new ParserXml();
				List<CultureItem> items = null;
				try {
					Log.d(TAG, "Calling parser");
					items = DataAccessFactory.getInstance()
							.getAreaItems(
									String.valueOf((myPosition.getLongitudeE6() - (length / 2)) / 1E6)
									,String.valueOf((myPosition.getLatitudeE6() - (height / 2)) / 1E6),
									String.valueOf((myPosition.getLongitudeE6() + (length / 2)) / 1E6),
									String.valueOf((myPosition.getLatitudeE6() + (height / 2)) / 1E6)
									);
				} catch (Exception e) {
					Log.e(TAG, "Error loading items1", e);
					errorMessage = e.toString();
					
				}

				try {
					if (items == null || items.size() <= 5) {
						Log.d(TAG, "Calling parser - due to null or size <=5 ");
						items = DataAccessFactory.getInstance()
								.getAreaItems(
										String.valueOf((myPosition
												.getLongitudeE6() - (2 * length)) / 1E6),
										String.valueOf((myPosition
												.getLatitudeE6() - (2 * height)) / 1E6),
										String.valueOf((myPosition
														.getLongitudeE6() + (2 * length)) / 1E6),
										String.valueOf((myPosition
												.getLatitudeE6() + (2 * height)) / 1E6)
										);

					}
				} catch (Exception e) {
					Log.e(TAG, "Error loading items2", e);
					errorMessage = e.toString();
				}
				return items;
			}
			@Override
			protected void onPostExecute(List<CultureItem> result) {
				super.onPostExecute(result);
				if(listener != null){
					if(result != null){
						listener.onCultureItemsReceived(result);
						recentMapItems = result;
					}
					else{
						listener.onCultureItemFailed(errorMessage);
					}
					
				}
			}
		};
		task.execute(mapCenter, height, width);
		
	}

	
	
	public void addCultureItem(CultureItem item, Bitmap image, final AddCultureItemListener listener){
		
		AsyncTask<Object, Void, Boolean> task = new AsyncTask<Object, Void, Boolean>(){
			
			private AddCultureItemListener mListener = listener;
			private String error;
			protected Boolean doInBackground(Object... params) {
				
				//Parsning
				CultureItem item = (CultureItem)params[0];
				Bitmap image = (Bitmap)params[1];
				
				try {
					DataAccessFactory.getInstance().addCultureItem(item, image);
				} catch (Exception e) {
					return false;
				}
				//float e6 = 1000*1000;
				//CultureItem fetchedItem = new CultureItem(CultureItemType.KSamItemType, new GeoPoint((int)(59*e6), (int)(18*e6)));
				//fetchedItem.setDescription("Test Description");
				return true;
			}
			
			@Override
			protected void onPostExecute(Boolean result) {
				super.onPostExecute(result);
				if(mListener != null){
					
					if(result == true){
						mListener.onCultureItemAdded();
					} else {
						mListener.onCultureItemAddFail(error);
					}
				}
			}
		};
		
		task.execute(item, image);
		
	}
	
	public void getDetails(String id, final DataAccessManager.CultureItemListener listener) {
		AsyncTask<Object, Void, CultureItem> task = new AsyncTask<Object, Void, CultureItem>(){
	
			private String error;
			private DataAccessManager.CultureItemListener mListener = listener;

			protected CultureItem doInBackground(Object... params) {
				String id = (String)params[0];
				
				
				//id = "http://kulturarvsdata.se/raa/fmi/10249700130001";
				id = id.replace(":", "%3A");
				id = id.replace("/", "%C2%BD");
				CultureItem fetchedItem = null;
				try {
					fetchedItem = DataAccessFactory.getInstance().getItemDetail(id);
				} catch (Exception e) {
					Log.e(TAG, "Error loading Details", e);
					error = e.getMessage();
					
				}
				return fetchedItem;
			}
			
			@Override
			protected void onPostExecute(CultureItem result) {
				super.onPostExecute(result);
				if(result != null){
					
					mListener.onCultureItemReceived(result);
					
				}
				else{
					mListener.onCultureItemReceiveFailed(error);
				}
			}
		};
		
		task.execute(id);
	}

	
	
}
